#AIQuestionAnswer.py

from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit, QLineEdit, QPushButton, QVBoxLayout, QWidget
from PySide6.QtCore import Qt, QThread, Signal
import sys

class APICaller(QThread):
    response_signal = Signal(str)

    def __init__(self, question):
        super().__init__()
        self.question = question

    def run(self):
        # 模拟调用AI接口
        response = call_ai_api(self.question)
        self.response_signal.emit(response)

def call_ai_api(question):
    return f"这是对问题 '{question}' 的回答。"

class AIQuestionAnswerWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("AI问答窗口")
        self.setGeometry(100, 100, 800, 600)

        # 创建控件
        self.text_display = QTextEdit(self)
        self.text_display.setReadOnly(True)  # 设置为只读
        self.text_input = QLineEdit(self)
        self.text_input.setPlaceholderText("请输入您的问题...")
        self.submit_button = QPushButton("提交", self)

        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(self.text_display)
        layout.addWidget(self.text_input)
        layout.addWidget(self.submit_button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        # 绑定按钮点击事件
        self.submit_button.clicked.connect(self.on_submit_clicked)

    def on_submit_clicked(self):
        user_input = self.text_input.text().strip()
        if not user_input:
            return  # 如果输入为空则直接返回

        # 显示加载指示器
        self.text_display.append(f"问题: {user_input}")
        self.text_display.append("正在处理...")

        # 异步调用AI接口
        self.api_caller = APICaller(user_input)
        self.api_caller.response_signal.connect(self.display_response)
        self.api_caller.start()

    def display_response(self, response):
        self.text_display.append(f"回答: {response}\n")
        self.text_input.clear()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AIQuestionAnswerWindow()
    window.show()
    sys.exit(app.exec())